package com.wf.ew.store.controller;


import com.wangfan.endecrypt.utils.EndecryptUtils;
import com.wf.ew.common.JsonResult;
import com.wf.ew.common.utils.ByteUtil;
import com.wf.ew.system.model.User;
import com.wf.ew.system.service.AuthoritiesService;
import com.wf.ew.system.service.UserRoleService;
import com.wf.ew.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.provider.TokenStore;

@Api(value = "商店用户登录", tags = "store_user")
@RestController
@RequestMapping("store/user")
public class StoreUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private AuthoritiesService authoritiesService;
    @Autowired
    private UserRoleService userRoleService;


    @ResponseBody
    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/login")
    public JsonResult login(String phone, String password) {
        User user = userService.getByPhone(phone);
        if (user == null) {
            return JsonResult.error("无账号");
        } else if (!user.getPassword().equals(EndecryptUtils.encrytMd5(password))) {
            return JsonResult.error("密码错误");
        } else if (user.getState() != 0) {
            return JsonResult.error("账号被锁定");
        }
        String[] roles = ByteUtil.arrayToString(userRoleService.getRoleIds(user.getUserId()));
        String[] permissions = ByteUtil.listToArray(authoritiesService.listByUserId(user.getUserId()));
        Token token = tokenStore.createNewToken(String.valueOf(user.getUserId()), permissions, roles);
        return JsonResult.ok("登录成功").put("access_token", token.getAccessToken());
    }


}
